package com.xzlf.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xzlf.util.RSAProperties;
import com.xzlf.util.RSAUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Set;

@Component
@Aspect
@Slf4j
@Order(0)
public class EncrptAspt {

    @Autowired
    private RSAProperties rsaProperties;

    @Pointcut("execution( * com.xzlf.conttoller.*.*(..))")
    public void encryptParam(){}

    @Around("encryptParam()")
    public Object encryptDecrypt(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("=====================进入拦截器===============");
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        log.info("=====================请求url:{}, uri:{}===============", request.getRequestURL(), request.getRequestURI());
        HttpServletResponse response = requestAttributes.getResponse();
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (Map.Entry<String, String[]> stringEntry : parameterMap.entrySet()) {
            log.info("=======入参:{}--{}=============", stringEntry.getKey(), stringEntry.getValue());
        }
        R ret = (R) joinPoint.proceed();
        log.info("====方法返回值：{}========", JSON.toJSONString(ret));
        Object data = ret.getData();
        String s = RSAUtil.encryptedDataOnJava(JSON.toJSONString(data), rsaProperties.getPublicKey());
       ret.setData(s);
        log.info("====方法返回值：{}========", JSON.toJSONString(ret));
        return ret;
    }
}
